﻿using Freebase4net.Bases;
using Freebase4net.Rest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Freebase4net
{
    public class ImageService
    {
        private string _apiKey;
        private MqlReadService _readService;

        public ImageService(string ApiKey)
        {
            _apiKey = ApiKey;
            _readService = FreebaseServices.CreateMqlReadService();
        }


        public string GetImageUrl(string id, string fallbackid = "", string maxheight = "", string maxwidth = "", ImageServiceMode mode = ImageServiceMode.None, bool pad = false)
        {
            StringBuilder result = new StringBuilder();

            result.AppendFormat("{0}{1}?", Constants.ImageServiceUrl, id);
            result.Append(CheckParameter("key", _apiKey));
            result.Append(CheckParameter("maxheight", maxheight));
            result.Append(CheckParameter("maxwidth", maxwidth));
            result.Append(CheckParameter("mode", ServicesHelpers.GetImageMode(mode)));
            result.Append(CheckParameter("fallbackid", fallbackid));
            result.Append(CheckParameter("pad", pad ? "1" : ""));

            return result.ToString();
        }

        public Task<Stream> DownloadImageAsync(string id)
        {
            HttpClient client = new HttpClient();
            return client.GetStreamAsync(GetImageUrl(id));
        }

        public async Task<bool> CheckIfImageExistAsync(string id)
        {
            dynamic query = new ExpandoObject();
            query.id = id;
            ((IDictionary<String, Object>)query).Add("/common/topic/image", new Dictionary<Object, Object>() {
                                                                                               {"id",null}    
                                                                                            });
            MqlReadServiceResponse response = await _readService.ReadAsync(query);
            if (response.Results.Count > 0)
            {
                return true;
            }
            return false;
        }

        public async Task<bool> SaveImageAsync(string id, string fileName, bool checkFoNoImage = false)
        {
            bool shouldSaveImage = true;

            try
            {
                if (checkFoNoImage)
                    shouldSaveImage = await CheckIfImageExistAsync(id);

                if (shouldSaveImage)
                {
                    var stream = await DownloadImageAsync(id);
                    Utils.CopyStreamToFile(stream, fileName);
                }

                return shouldSaveImage;
            }
            catch (Exception e)
            {
                return false;   
            }
        }

        private string CheckParameter(string key, string value)
        {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                return string.Format("{0}={1}&", key, value);
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
